<template>
	<view class="container">
		<uniDatetimePicker v-model="timeRange" type="daterange" rangeSeparator="至" @change="reset()">
		</uniDatetimePicker>
		<view class="scan-result">扫描结果：{{total}}条记录</view>
		<!-- <button class="scan-btn" type="default" @click="scanCode()">开始扫描</button> -->
		<button class="scan-btn" type="default" @click="openModal">手动录入</button>
		<!-- #ifdef APP-PLUS -->
		<xw-scan></xw-scan>
		<!-- #endif -->

		<view class="table-container">
			<view class="table-header">
				<view class="table-cell header-cell">货品码</view>
				<view class="table-cell header-cell time-header" @click="toggleSort">
					添加时间
					<view class="sort-icon">
						<uni-icons v-if="sortOrder === 'asc'" type="arrow-up" size="16" color="#fff"></uni-icons>
						<uni-icons v-if="sortOrder === 'desc'" type="arrow-down" size="16" color="#fff"></uni-icons>
					</view>
				</view>
			</view>

			<view class="table-body">
				<view class="table-row" v-for="(item, index) in input" :key="index">
					<view class="table-cell code-cell">{{item.code}}</view>
					<view class="table-cell time-cell">{{item.time}}</view>
				</view>

				<view v-if="input.length === 0" class="empty-tip">
					<image src="/static/empty.png" mode="aspectFit"></image>
					<text>暂无扫描数据</text>
				</view>
			</view>
		</view>
		<!-- <view> -->
			<!-- <uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="info" cancelText="关闭" confirmText="同意" title="通知" content="是否退出当前账号"
					@confirm="dialogConfirm">
				</uni-popup-dialog>
			</uni-popup> -->
		<!-- </view> -->
		<uni-popup ref="manualInput" mode="center">
			<uni-popup-dialog type="info" cancelText="关闭" confirmText="提交" title="手动输入"
				@confirm="markSubmit">
				<uni-forms :model="form" ref="uForm" :rules="rules" immediate>
				  <uni-forms-item label="集货码">
				    <u-input v-model="form.markNumber" placeholder="请输入集货码" />
				  </uni-forms-item>
				</uni-forms>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		scanCode,
		getCode
	} from '../../config/api/api.js';
	import {
		getToken,
		login,
		logout
	} from '../../config/comm'
	import uniIcon from '../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
	import uniDatetimePicker from '../../uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue'
	import moment from 'moment'

	function formatDate(date) {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	export default {
		data() {
			return {
				input: [],
				audio: uni.createInnerAudioContext(),
				except_arr: [],
				sortOrder: 'desc',
				timeRange: [moment().subtract(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'), moment().format(
					'YYYY-MM-DD HH:mm:ss')],
				total: 1,
				page: 1,
				current: 1,
				form: {
					markNumber: ''
				},
				rules: {
					markNumber: [
						{
						required: true,
						message: '请输入集货码',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
						}
					]
				}
			}
		},
		components: {
			uniIcon,
			uniDatetimePicker
		},
		onLoad() {
			this.audio.src = '/static/25.mp3';
			this.audio.volume = 1;
			this.fetch(); // 初始化加载数据
		},
		onUnload() {
			// #ifdef APP-PLUS
			uni.$off('xwscan')
			// #endif
		},
		onPullDownRefresh() {
			if (this.current < this.page) {
				this.current++
				this.fetch()
			}
			uni.stopPullDownRefresh();
		},
		// onBackPress() {
		// 	this.$refs.alertDialog.open()
		// 	return true;
		// },
		onReachBottom() {
			if (this.current < this.page) {
				this.current++
				this.fetch()
			}
		},
		onShow() {
			// #ifdef APP-PLUS
			uni.$off('xwscan')
			uni.$on('xwscan', (res) => {
				this.handleScanResult(res.code);
			})
			// #endif
		},
		methods: {
			markSubmit() {
				// 先通过 uni-forms 的 validate 方法验证表单
				  this.$refs.uForm.validate().then(valid => {
				    if (valid) {
				      // 验证通过：调用扫码结果处理逻辑，传入手动输入的集货码
				      this.handleScanResult(this.form.markNumber);
				      // 提交后清空输入框，并关闭弹窗
				      this.form.markNumber = '';
				      this.$refs.manualInput.close();
				    } else {
				      // 验证失败：表单会自动提示错误（基于 rules 配置）
				      console.log('表单验证失败');
				    }
				  }).catch(err => {
				    console.error('表单验证异常：', err);
				  });
			},
			dialogConfirm() {
				try {
				    uni.hideLoading(); // 确保关闭任何可能存在的加载提示
				    uni.removeStorageSync('token')
				  } catch(e) {
				    console.log('e', e)
				  }
				  this.input = []
				  this.timeRange = [moment().subtract(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
				    moment().format('YYYY-MM-DD HH:mm:ss')
				  ]
				  this.total = 1
				  this.page = 1
				  this.current = 1
				  this.$refs.alertDialog.close()
				  uni.reLaunch({
				    url: '/pages/login/index/index'
				  });
			},
			reset() {
				this.current = 1
				this.input = []
				this.fetch()
			},
			toggleSort() {
				this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				this.reset();
			},
			async fetch() {
				uni.showLoading({
					title: '加载中...'
				});
				try {
					const {
						data: {
							data,
							last_page,
							total
						}
					} = await getCode({
						sort: 'add_time',
						order: this.sortOrder,
						...(this.timeRange ? {
							credate: `${moment(this.timeRange[0]).format('YYYY-MM-DD')},${moment(this.timeRange[1]).format('YYYY-MM-DD')}`
						} : {}),
						page: this.current,
					});
					if (data) {
						this.input.push(...data.map(el => ({
							code: el.bar_code,
							time: formatDate(new Date(el.add_time))
						})));
						this.total = total
						this.page = last_page
					}
				} catch (e) {
					console.error(e);
				} finally {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				}
			},
			async scanCode() {
				uni.scanCode({
					onlyFromCamera: true,
					success: (res) => {
						if (this.except_arr.includes(res.result)) {
							uni.showToast({
								title: '扫码重复',
								icon: 'none'
							})
						} else {
							this.handleScanResult(res.result);
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '扫描失败',
							icon: 'none'
						});
					}
				});
			},
			openModal () {
				// 打开弹窗前，确保规则已设置（若弹窗未渲染，$refs.uForm 可能为 undefined，需判断）
				  if (this.$refs.uForm) {
				    this.$refs.uForm.setRules(this.rules);
				  }
				  this.$refs.manualInput.open();
			},
			handleScanResult(result) {
				if (this.except_arr.includes(result)) {
					uni.showToast({
						title: '扫码重复',
						icon: 'none'
					})
				} else {
					const reg = /^[0-9]{6,18}\.[0-9]{1,3}$/;
					if (reg.test(result)) {
						scanCode({
							bar_code: 'J'+ result
						}).then((data) => {
							uni.showToast({
								title: '添加成功',
								icon: 'success'
							});
							// 播放扫码成功
							this.audio.play();
							 // 添加振动 - 震动1秒（1000毫秒）
							 // #ifdef APP-PLUS
							        if (plus.device.vibrate) {
							            plus.device.vibrate(1000); // 振动 1 秒
							        }
							// #endif
							this.except_arr.push(result);
							this.input.unshift({ // 新数据添加到开头
								code: data.data.bar_code,
								time: formatDate(new Date())
							});
							this.total++
						}).catch(e => {
							console.log('e', e)
							uni.showToast({
								title: '添加失败',
								icon: 'none'
							});
						});
					} else {
						uni.showToast({
							title: '条码格式不正确',
							icon: 'none'
						});
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.refresh-btn {
		background-color: #409eff;
		color: white;
		margin-bottom: 20rpx;
	}

	.scan-btn {
		background-color: #67c23a;
		color: white;
		margin-bottom: 30rpx;
	}

	.scan-result {
		font-size: 28rpx;
		color: #909399;
		margin: 20rpx 0;
		text-align: center;
	}

	/* 表格样式 */
	.table-container {
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 12rpx 0 rgba(0, 0, 0, 0.1);
	}

	.table-header {
		display: flex;
		background-color: #409eff;
	}

	.table-body {
		max-height: 70vh;
		overflow-y: auto;
	}

	.table-row {
		display: flex;
		border-bottom: 1rpx solid #ebeef5;
		transition: all 0.3s;

		&:last-child {
			border-bottom: none;
		}

		&:nth-child(odd) {
			background-color: #fafafa;
		}

		&:hover {
			background-color: #f5f7fa;
		}
	}

	.table-cell {
		flex: 1;
		padding: 24rpx;
		font-size: 28rpx;
		text-align: center;
		word-break: break-all;

		&.code-cell {
			color: #303133;
			font-weight: 500;
		}

		&.time-cell {
			color: #606266;
		}

		&.time-header {
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;

			.sort-icon {
				margin-left: 10rpx;
				display: flex;
				align-items: center;
			}
		}
	}

	.header-cell {
		color: #fff;
		font-weight: bold;
		font-size: 30rpx;
	}

	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
			opacity: 0.6;
		}

		text {
			color: #909399;
			font-size: 28rpx;
		}
	}

	/* 响应式调整 */
	@media (max-width: 500px) {
		.table-cell {
			padding: 20rpx 10rpx;
			font-size: 26rpx;
		}
	}
</style>